package com.frinder.demo2;

import akka.actor.OneForOneStrategy;
import akka.actor.Props;
import akka.actor.SupervisorStrategy;
import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.Function;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;

/**
 * Created by frinder on 2017/7/24.
 */
public class SuperVisor extends UntypedActor {

    LoggingAdapter logger = Logging.getLogger(getContext().system(), this);


    @Override
    public SupervisorStrategy supervisorStrategy() {
        return new OneForOneStrategy(3, Duration.create(1, TimeUnit.MINUTES),
                new Function<Throwable, SupervisorStrategy.Directive>() {
                    @Override
                    public SupervisorStrategy.Directive apply(Throwable t) throws Exception {
                        logger.error(t.getMessage(), t);
                        if (t instanceof ArithmeticException) {
                            return SupervisorStrategy.resume();
                        } else if (t instanceof NullPointerException) {
                            return SupervisorStrategy.restart();
                        } else if (t instanceof IllegalArgumentException) {
                            return SupervisorStrategy.stop();
                        }
                        return SupervisorStrategy.escalate();
                    }
                });
    }

    @Override
    public void onReceive(Object o) throws Exception {
        if (o instanceof Props) {
            getContext().actorOf((Props) o, "restartActor");
        } else {
            unhandled(o);
        }
    }
}
